package com.zm.campus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zm.campus.dao.ReplaceDoMapper;
import com.zm.campus.dao.UserMapper;
import com.zm.campus.pojo.ReplaceDo;
import com.zm.campus.pojo.RespBean;
import com.zm.campus.pojo.RespBeanEnum;
import com.zm.campus.pojo.Trade;
import com.zm.campus.dao.TradeMapper;
import com.zm.campus.query.TradeQuery;
import com.zm.campus.service.ITradeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zm.campus.util.AssertUtil;
import com.zm.campus.vo.DealingReturnVo;
import com.zm.campus.vo.ReplaceDoReturnVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.io.IOException;
import java.sql.Wrapper;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zm
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade> implements ITradeService {

    @Autowired
    private TradeMapper tradeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ReplaceDoMapper replaceDoMapper;
    //获取当前用户的进行中的订单
    @Override
    public RespBean getDealingData(TradeQuery tradeQuery) {
        System.out.println(tradeQuery.toString());
        AssertUtil.isTrue(StringUtils.isBlank(tradeQuery.getUserId())||userMapper
                .selectById(tradeQuery.getUserId())==null, RespBeanEnum.LoginUserError);
        //准备一个map
        Map<String,Object> map=new HashMap<>();
        //开启分页
        PageHelper.startPage(tradeQuery.getPage(),tradeQuery.getLimit());
        PageInfo<DealingReturnVo> pageInfo=new PageInfo<>(tradeMapper.queryAllReplaceDo(tradeQuery));
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return RespBean.success(map);
    }

    @Transactional
    //完成、取消订单
    @Override
    public RespBean doDeal(String userId, String tradeNo, Boolean doDeal) throws IOException {
        Trade dbTrade = tradeMapper.selectOne(new QueryWrapper<Trade>().eq("trade_no", tradeNo));
        AssertUtil.isTrue(null==dbTrade,RespBeanEnum.TradeIsNotExist);
        AssertUtil.isTrue(dbTrade.getState()==1,RespBeanEnum.TradeIsSuccess);//订单已完成，不能操作
        AssertUtil.isTrue(dbTrade.getState()==2,RespBeanEnum.TradeIsCancel);//订单已取消
        ReplaceDo replaceDo = replaceDoMapper.selectOne(new QueryWrapper<ReplaceDo>().eq("id", dbTrade.getReplaceId()));
        AssertUtil.isTrue(!( dbTrade.getTrUserId().equals(userId)|| replaceDo.getRdUserId().equals(userId))
                ,RespBeanEnum.DoDealIsNoTrUser);
        if (doDeal){//完成订单
            replaceDo.setState(3);
            dbTrade.setEndDate(new Date());
            dbTrade.setState(1);//完成订单
            AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)+tradeMapper.updateById(dbTrade)!=2
                    ,RespBeanEnum.UpdateError);
            //向前端用户推送订单完成消息
            if(dbTrade.getTrUserId().equals(userId)){//说明是接单人进行操作的订单,则给发布者推送消息
                WebSocketServer.sendInfo("订单完成",replaceDo.getRdUserId());
            }else {//说明是发布者完成的订单，则给接单人推送消息
                WebSocketServer.sendInfo("订单完成",dbTrade.getTrUserId());
            }
            ResponseEntity.status(HttpStatus.OK).build();
            return RespBean.success();
        }else {//取消订单,若截止时间在当前时间的1小时后，则让该订单重新进入代劳列表，否则就丢弃该订单（让发布者重新发布）
            Date now=new Date();
            dbTrade.setState(2);
            dbTrade.setEndDate(new Date());
            if (replaceDo.getEndDate().before(new Date(now.getTime()+3600000))){//说明已经超过重新进入代劳列表的条件了，丢弃
                replaceDo.setState(3);//置为完成状态
                AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)!=1
                        ,RespBeanEnum.UpdateError);//执行更新操作
            }else {//向前端用户推送订单取消消息
                //这里要发送一个信息给发布者，让起判断是否要重新把消息放入代劳信息中，若用户运行再把代劳状态设置为1（待接单）
                WebSocketServer.sendInfo("重新代劳",replaceDo.getRdUserId());
                ResponseEntity.status(HttpStatus.OK).build();
            }
            AssertUtil.isTrue(tradeMapper.updateById(dbTrade)!=1
                    ,RespBeanEnum.UpdateError);//执行更新操作
            //给对方发送订单被取消的消息
            if (dbTrade.getTrUserId().equals(userId)){
                WebSocketServer.sendInfo("订单取消",replaceDo.getRdUserId());
            }else {
                WebSocketServer.sendInfo("订单取消",dbTrade.getTrUserId());
            }
            ResponseEntity.status(HttpStatus.OK).build();
            return  RespBean.success();
        }
    }

    //是否重新代劳
    @Transactional
    @Override
    public RespBean reDeal(String rdId, boolean isDeal) {//代劳id
        AssertUtil.isTrue(StringUtils.isBlank(rdId),RespBeanEnum.DoDealParamsNull);
        ReplaceDo replaceDo = replaceDoMapper.selectById(rdId);
        Trade trade= tradeMapper.selectByRdId(rdId);
        AssertUtil.isTrue(trade==null||replaceDo==null,RespBeanEnum.RDInfoIsOverdue);
        int temp=0;
        if (isDeal){//用户确认重新发布
            Date now=new Date();
            if (replaceDo.getEndDate().after(new Date(now.getTime()+3600000))) {//截止时间不能小于1各小时
                replaceDo.setState(1);//待接单
                temp = tradeMapper.deleteById(trade.getId());//删除旧的接单信息
            }else {
                replaceDo.setState(3);
                AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)!=1,RespBeanEnum.SystemBusy);
                return RespBean.error(RespBeanEnum.RdTimeIsToShort);
            }
        }else {
            replaceDo.setState(3);
            temp = temp+1;
        }
        AssertUtil.isTrue(replaceDoMapper.updateById(replaceDo)+temp!=2,RespBeanEnum.SystemBusy);
        return RespBean.success();
    }

}
